package com.example.newspublish.service;

import io.minio.GetPresignedObjectUrlArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.SetBucketPolicyArgs;
import io.minio.errors.MinioException;
import io.minio.http.Method;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@Service
public class FileUploadService {

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucket-name}")
    private String bucketName;

    public String uploadImage(MultipartFile file) throws Exception {
//        String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
        String fileName = file.getOriginalFilename();
        System.out.println("上传文件："+file.getOriginalFilename());
        try {
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object(fileName)
                            .contentType(file.getContentType())
                            .stream(file.getInputStream(), file.getSize(), -1)
                            .build()
            );

            //预签名获取
            GetPresignedObjectUrlArgs args = GetPresignedObjectUrlArgs.builder()
                    .bucket(bucketName)
                    .object(fileName)
                    .expiry(7*86400) // URL的过期时间为1小时
                    .method(Method.GET) // 使用GET方法
                    .build();
            String url = minioClient.getPresignedObjectUrl(args);

            return url;

        } catch (MinioException | InvalidKeyException | NoSuchAlgorithmException e) {
            throw new Exception("Error uploading file to MinIO: " + e.getMessage());
        }
    }
}
